<?php

$config = [
    'ins_cd' => '08A9999999', //机构号
    'mchnt_cd' => '0002900F0370542', //商户号
    'term_id' => '88888888', //终端号
    'sub_appid' => '', //子商户appid
    'private_key' => '-----BEGIN RSA PRIVATE KEY-----  
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJgAzD8fEvBHQTyxUEeK963mjziM
WG7nxpi+pDMdtWiakc6xVhhbaipLaHo4wVI92A2wr3ptGQ1/YsASEHm3m2wGOpT2vrb2Ln/S7lz1
ShjTKaT8U6rKgCdpQNHUuLhBQlpJer2mcYEzG/nGzcyalOCgXC/6CySiJCWJmPyR45bJAgMBAAEC
gYBHFfBvAKBBwIEQ2jeaDbKBIFcQcgoVa81jt5xgz178WXUg/awu3emLeBKXPh2i0YtN87hM/+J8
fnt3KbuMwMItCsTD72XFXLM4FgzJ4555CUCXBf5/tcKpS2xT8qV8QDr8oLKA18sQxWp8BMPrNp0e
pmwun/gwgxoyQrJUB5YgZQJBAOiVXHiTnc3KwvIkdOEPmlfePFnkD4zzcv2UwTlHWgCyM/L8SCAF
clXmSiJfKSZZS7o0kIeJJ6xe3Mf4/HSlhdMCQQCnTow+TnlEhDTPtWa+TUgzOys83Q/VLikqKmDz
kWJ7I12+WX6AbxxEHLD+THn0JGrlvzTEIZyCe0sjQy4LzQNzAkEAr2SjfVJkuGJlrNENSwPHMugm
vusbRwH3/38ET7udBdVdE6poga1Z0al+0njMwVypnNwy+eLWhkhrWmpLh3OjfQJAI3BV8JS6xzKh
5SVtn/3Kv19XJ0tEIUnn2lCjvLQdAixZnQpj61ydxie1rggRBQ/5vLSlvq3H8zOelNeUF1fT1QJA
DNo+tkHVXLY9H2kdWFoYTvuLexHAgrsnHxONOlSA5hcVLd1B3p9utOt3QeDf6x2i1lqhTH2w8gzj
vsnx13tWqg==
-----END RSA PRIVATE KEY-----', //RSA私钥
    'notify_url' => 'www.test.com', //通知地址
    'use_sandbox' => false,
    'return_raw' => false
];

/**
 * 获取用户IP及端口号
 * @param bool $port 是否获取端口号
 * @param bool $portJoin 端口号是否追加至IP后
 * @return string
 * @author KingRainy <kingrainy@163.com>
 */
function getIp($port = false, $portJoin = false)
{
    $realip = '';
    $unknown = '127.0.0.1';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($arr as $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } else if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $realip = $_SERVER['REMOTE_ADDR'];
        } else {
            $realip = $unknown;
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)) {
            $realip = getenv("REMOTE_ADDR");
        } else {
            $realip = $unknown;
        }
    }
    $matches = array();
    $ipMatches = preg_match("/[\d\.]{7,15}/", $realip, $matches);
    if ($ipMatches) {
        $realip = $matches[0];
    } else {
        $realip = $unknown;
    }
    if ($port) {
        $ipport = intval($_SERVER['REMOTE_PORT'] ?? 0);
        if ($portJoin) {
            $realip = $realip . ':' . $ipport;
        } else {
            return $ipport;
        }
    }
    return $realip;
}

/**
 * 随机生成字符串
 * @param mixed $length 长度
 * @param bool $numeric 仅为数字
 * @return string
 * @author wangyu <wangyu@ledouya.com>
 * @createTime 2018/3/21 18:40
 */
function random($length, $numeric = false)
{
    $seed = base_convert(md5(microtime() . ($_SERVER['DOCUMENT_ROOT']) ?? getIp(true, true)), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    if ($numeric) {
        $hash = '';
    } else {
        $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
        $length--;
    }
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

/**
 * 生成32位随机字符串
 * @return string
 * @author wangyu <wangyu@ledouya.com>
 * @createTime 2018/5/12 15:19
 */
function uuid32()
{
    $uuid = md5(uniqid(md5(microtime(true)), true));
    return $uuid;
}

/**
 * 全局唯一标识符(uuid实现)
 * @param string $namespace 自定义命名空间
 * @return string
 * @author wangyu <wangyu@ledouya.com>
 * @createTime 2018/7/19 11:33
 */
function guid($namespace = '')
{
    $data = ($_SERVER['REQUEST_TIME_FLOAT'] ?? ($_SERVER['REQUEST_TIME'] ?? time())) . ($_SERVER['REMOTE_ADDR'] ?? getIp(true, true));
    $hash = strtoupper(hash('ripemd128', uuid32() . md5($namespace . $data)));
    return substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
}

/**
 * 订单号生成（32位字符串）
 * @param null $custom 自定义字符，需为大于0小于100的数字，可用来做业务方自定义数据使用
 * @param bool $simple 是否采用简单模式
 * @return string
 * @author wangyu <wangyu@ledouya.com>
 * @createTime 2018/4/25 15:50
 */
function trade_no($custom = null, $simple = false)
{
    list($usec, $sec) = explode(' ', microtime());
    $usec = substr(str_replace('0.', '', $usec), 0, 6);
    if (false === $simple) {
        if (!empty($custom) && $custom > 0 && $custom < 99) {
            $custom = str_pad($custom, 2, '0', STR_PAD_LEFT);
        } else {
            $custom = rand(10, 99);
        }
        $str = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
        return date('YmdHis') . $usec . $str . $custom;
    }
    $str = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $usec . $str . ($custom ?? '');
}